package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qianying.comment.CommonResult;
import com.qianying.entity.CustomerInfo;
import com.qianying.entity.ShopInfo;
import com.qianying.mapper.CustomerInfoMapper;
import com.qianying.mapper.ShopInfoMapper;
import com.qianying.service.ChinaAreaService;
import com.qianying.service.CustomerInfoService;
import com.qianying.service.RegionService;
import com.qianying.service.ShopInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.*;
import java.util.stream.Stream;

/**
 * 店铺信息服务实现类
 * 实现店铺信息的业务逻辑，包含完整的参数空值判断
 *
 * @author check
 * @date 2025-08-01
 */
@Service
public class ShopInfoServiceImpl implements ShopInfoService {

    @Autowired
    private ShopInfoMapper shopInfoMapper;

    @Autowired
    private RegionService regionService;

    @Autowired
    private CustomerInfoService customerInfoService;

    @Autowired
    private ChinaAreaService chinaAreaService;

    /**
     * 根据ID查询店铺信息（含关联数据）
     *
     * @param id 店铺ID
     * @return 包含店铺信息的通用结果
     */
    @Override
    public CommonResult<ShopInfo> getById(Long id) {
        // 1. 校验ID是否为空
        if (id == null) {
            return CommonResult.failed("查询失败：店铺ID不能为空");
        }

        // 2. 查询店铺基本信息及关联数据
        ShopInfo shopInfo = shopInfoMapper.selectById(id);

        // 3. 校验查询结果
        if (shopInfo == null) {
            return CommonResult.failed("查询失败：未找到ID为" + id + "的店铺信息");
        }

        //设置地理信息
        CommonResult<Map<Long, String>> regionResult = regionService.getRegionMapByCustomerId(shopInfo.getCustomerId());
        if (regionResult.isSuccess()) {
            Map<Long, String> map = regionResult.getData();
            if (!map.isEmpty()) {
                if (map.containsKey(shopInfo.getProvinceId())) {
                    shopInfo.setProvinceName(map.get(shopInfo.getProvinceId()));
                }

                if (map.containsKey(shopInfo.getCityId())) {
                    shopInfo.setCityName(map.get(shopInfo.getCityId()));
                }

                if (map.containsKey(shopInfo.getDistrictId())) {
                    shopInfo.setDistrictName(map.get(shopInfo.getDistrictId()));
                }
            }
        }

        CustomerInfo customerInfoRes = customerInfoService.getById(shopInfo.getCustomerId());
        if (customerInfoRes != null) {
            shopInfo.setCustomerName(customerInfoRes.getCustomerName());
        }

        return CommonResult.success(shopInfo);
    }

    /**
     * 根据客户ID分页查询店铺信息（含关联数据）
     *
     * @param page       分页参数
     * @param customerId 客户ID（必选搜索条件）
     * @return 包含分页店铺列表的通用结果
     */
    @Override
    public CommonResult<IPage<ShopInfo>> getPageByCustomerId(Page<ShopInfo> page, Long customerId, String shopName,
                                                             Integer status) {
        // 1. 校验分页参数
        if (page == null) {
            return CommonResult.failed("查询失败：分页参数不能为空");
        }

        // 2. 校验客户ID
        if (customerId == null) {
            return CommonResult.failed("查询失败：客户ID不能为空");
        }

        // 3. 构建查询条件
        LambdaQueryWrapper<ShopInfo> queryWrapper = Wrappers.lambdaQuery();
        // 必选条件：客户ID
        queryWrapper.eq(ShopInfo::getCustomerId, customerId);

        if (shopName != null && !shopName.trim().isEmpty()) {
            queryWrapper.like(ShopInfo::getShopName, shopName);
        }

        if (status != null) {
            queryWrapper.eq(ShopInfo::getStatus, status);
        }

        // 排序条件
        queryWrapper.orderByDesc(ShopInfo::getCreateTime);

        // 4. 执行分页查询（使用基础BaseMapper的分页方法，后续可在mapper中扩展关联查询方法）
        IPage<ShopInfo> shopPage = shopInfoMapper.selectPage(page, queryWrapper);

        // 5. 如果需要关联数据，在这里补充处理（如大区、省市区名称）
        if (shopPage.getRecords() != null && !shopPage.getRecords().isEmpty()) {
            List<ShopInfo> shopList = shopPage.getRecords();

            CommonResult<Map<Long, String>> regionResult = regionService.getRegionMapByCustomerId(customerId);
            Map<Long, String> map = regionResult.getData();

            CustomerInfo customerInfo = customerInfoService.getById(customerId);
            String customName = customerInfo.getCustomerName();

            //设置区域信息和客户名称
            for (ShopInfo shopInfo : shopList) {
                if (!map.isEmpty()) {
                    if (map.containsKey(shopInfo.getProvinceId())) {
                        shopInfo.setProvinceName(map.get(shopInfo.getProvinceId()));
                    }

                    if (map.containsKey(shopInfo.getCityId())) {
                        shopInfo.setCityName(map.get(shopInfo.getCityId()));
                    }

                    if (map.containsKey(shopInfo.getDistrictId())) {
                        shopInfo.setDistrictName(map.get(shopInfo.getDistrictId()));
                    }
                }
                shopInfo.setCustomerName(customName);
            }

        }

        return CommonResult.success(shopPage);
    }

    @Override
    /**
     * 分页查询所有店铺列表（含关联信息）
     * 关联查询区域名称、客户名称、省市区名称
     *
     * @param page      分页参数
     * @param shopName  店铺名称（模糊查询）
     * @param status    店铺状态（精确匹配）
     * @return 带关联信息的分页结果
     */
    public CommonResult<IPage<ShopInfo>> getPageAllShopList(Page<ShopInfo> page, String shopName, Integer status) {
        try {
            // 1. 分页参数校验与默认值设置
            if (page == null) {
                page = new Page<>(1, 10);
            }
            page.setCurrent(Math.max(page.getCurrent(), 1));
            page.setSize(Math.min(Math.max(page.getSize(), 1), 100));

            // 2. 构建查询条件
            LambdaQueryWrapper<ShopInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.hasText(shopName)) {
                queryWrapper.like(ShopInfo::getShopName, shopName.trim());
            }
            if (status != null) {
                queryWrapper.eq(ShopInfo::getStatus, status);
            }
            queryWrapper.orderByDesc(ShopInfo::getCreateTime);

            // 3. 执行分页查询（含关联信息）
            IPage<ShopInfo> shopPage = shopInfoMapper.selectPage(page, queryWrapper);

            // 4. 批量查询关联数据（优化数据库交互，避免N+1问题）
            if (!shopPage.getRecords().isEmpty()) {
                // 4.1 收集所有关联ID

                Map<Long, String> regionNameMap = regionService.getRegionMap();
                Map<Long, String> customerNameMap = customerInfoService.getAllCustomerIdNameMap();
                Map<Long, String> areaNameMap = chinaAreaService.IdToNameMap();


                // 4.3 填充关联名称到店铺对象
                for (ShopInfo shop : shopPage.getRecords()) {
                    // 区域名称
                    shop.setRegionName(regionNameMap.getOrDefault(shop.getRegionId(), ""));
                    // 客户名称
                    shop.setCustomerName(customerNameMap.getOrDefault(shop.getCustomerId(), ""));
                    // 省市区名称
                    shop.setProvinceName(areaNameMap.getOrDefault(shop.getProvinceId(), ""));
                    shop.setCityName(areaNameMap.getOrDefault(shop.getCityId(), ""));
                    shop.setDistrictName(areaNameMap.getOrDefault(shop.getDistrictId(), ""));
                }
            }

            return CommonResult.success(shopPage, "查询成功");
        } catch (Exception e) {
            return CommonResult.failed("查询失败：" + e.getMessage());
        }
    }

    /**
     * 新增大区信息
     *
     * @param shopInfo 店铺信息实体
     * @return 包含新增结果的通用结果
     */
    @Override
    public CommonResult<ShopInfo> save(ShopInfo shopInfo) {
        // 1. 校验实体是否为空
        if (shopInfo == null) {
            return CommonResult.failed("新增失败：店铺信息不能为空");
        }

        if (shopInfo.getShopName() == null || shopInfo.getShopName().trim().isEmpty()) {
            return CommonResult.failed("新增失败：店铺名称不能为空");
        }

        // 3. 新增前处理（重置ID确保自增）
        shopInfo.setId(null);

        if (shopInfo.getProvinceId() == null || shopInfo.getCityId() == null || shopInfo.getDistrictId() == null) {
            return CommonResult.failed("新增失败：地区信息不能为空！");
        }
        try {
            // 4. 执行新增操作
            int insertCount = shopInfoMapper.insert(shopInfo);
            if (insertCount <= 0) {
                return CommonResult.failed("新增失败：数据库操作异常");
            }
        } catch (BadSqlGrammarException e) {
            return CommonResult.failed("新增失败！");
        }


        // 5. 返回新增结果（包含自动生成的ID）
        return CommonResult.success(shopInfo, "新增成功");
    }

    /**
     * 根据ID更新店铺信息
     *
     * @param shopInfo 店铺信息实体（含ID）
     * @return 包含更新结果的通用结果
     */
    @Override
    public CommonResult<?> updateById(ShopInfo shopInfo) {
        // 1. 校验实体是否为空
        if (shopInfo == null) {
            return CommonResult.failed("更新失败：店铺信息不能为空");
        }

        // 2. 校验ID是否为空
        if (shopInfo.getId() == null) {
            return CommonResult.failed("更新失败：店铺ID不能为空");
        }

        if (shopInfo.getShopName() == null || shopInfo.getShopName().trim().isEmpty()) {
            return CommonResult.failed("更新失败：店铺名称不能为空");
        }

        if (shopInfo.getProvinceId() == null || shopInfo.getCityId() == null || shopInfo.getDistrictId() == null) {
            return CommonResult.failed("更新失败：地区信息不能为空！");
        }

        // 4. 校验记录是否存在
        ShopInfo existingShop = shopInfoMapper.selectById(shopInfo.getId());
        if (existingShop == null) {
            return CommonResult.failed("更新失败：未找到ID为" + shopInfo.getId() + "的店铺信息");
        }

        // 5. 执行更新操作
        int updateCount = shopInfoMapper.updateById(shopInfo);
        if (updateCount <= 0) {
            return CommonResult.failed("更新失败：数据库操作异常或数据未发生变化");
        }

        return CommonResult.success(null, "更新成功");
    }

    /**
     * 根据ID删除店铺信息
     *
     * @param id 店铺ID
     * @return 包含删除结果的通用结果
     */
    @Override
    public CommonResult<?> removeById(Long id) {
        // 1. 校验ID是否为空
        if (id == null) {
            return CommonResult.failed("删除失败：店铺ID不能为空");
        }

        // 2. 校验记录是否存在
        ShopInfo existingShop = shopInfoMapper.selectById(id);
        if (existingShop == null) {
            return CommonResult.failed("删除失败：未找到ID为" + id + "的店铺信息");
        }

        // 3. 执行删除操作
        int deleteCount = shopInfoMapper.deleteById(id);
        if (deleteCount <= 0) {
            return CommonResult.failed("删除失败：数据库操作异常");
        }

        return CommonResult.success(null, "删除成功");
    }
}
